<?php
/* 兑换 */
namespace Api\Controller;
use Think\Controller;
use Think\Log;
class PExchangeController extends Controller {
 	
 	private $user = array();
 	private $scoreType = array(1=>'报名',2=>'导入', 3=>'兑换', 4=>'抽奖', 5=>'分享', 6=>'签到', 7=>'连续签到');
	public function __construct()
	{
		//解决跨域
		echoHeader();
		$phone = I('post.phone', '', 'trim');
		// $phone = '13660392546';
		$this->user = session('p_user');
		if(!$this->user or $this->user['phone'] != $phone){
			$this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请先登录'));
		}
        $this->user = M("PUser")->where(array("phone"=>$phone, "is_deleted"=>0))->find();
		if (!$this->user) {
			$this->ajaxReturn(array('err_code'=>10000, 'err_msg'=>'请先登录'));
		}
        $this->user['score']=user_score_sum($this->user['id']);
	}

	public function index()
	{
		$map['is_deleted'] = 0;
		$map['is_show'] = 1;
		$type = I('post.type', 0, 'intval');
		$pageSize = 100;
		$pageIndex = I('post.page', 1, 'intval');
		if ($type > 0) {
			$map['type'] = $type;
		}else {
			$map['type'] = array('NEQ',4);
		}
		$total = M("PExchange")->where($map)->count();
		$order = I('post.order', 'decs', 'trim');
		$order = strtolower($order);
		if(!in_array($order, array('desc', 'asc'))){
			$order = 'desc';
		}
		$page = $this->pagination($total, $pageSize ,$pageIndex);

		if($total){
			$list = M("PExchange")->field('id,name,url,sku,score,type,top,material')->where($map)
					->order('score '.$order.',top desc')->select();
		}else{
			$list = array();
		}
		$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>array('score'=>$this->user['score'], 'list'=>$list,'page'=>$page)));

	}

	public function indexForSpecial()
	{
		$map['is_deleted'] = 0;
		$map['is_show'] = 1;
		$map['type'] = 4;
		$pageSize = 100;
		$pageIndex = I('post.page', 1, 'intval');
		$total = M("PExchange")->where($map)->count();
		$order = I('post.order', 'decs', 'trim');
		$order = strtolower($order);
		if(!in_array($order, array('desc', 'asc'))){
			$order = 'desc';
		}
		$page = $this->pagination($total, $pageSize ,$pageIndex);

		if($total){
			$list = M("PExchange")->field('id,name,url,sku,score,type,desc,link')->where($map)
					->limit($page['offset'], $page['limit'])->order('score '.$order)->select();
            foreach ($list as $k => $v) {
				$list[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
			}

		}else{
			$list = array();
		}
		$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>array('score'=>$this->user['score'], 'list'=>$list,'page'=>$page)));

	}

	//报名活动
	public function enroll()
	{
		$id = I('post.id', 0, 'intval');
		$map['id'] = $id;
		$map['is_deleted'] = 0;
		$map['status'] = 1;
		$act = M("PActivity")->where($map)->find();
		if (!$act) {
			$this->ajaxReturn(array('err_code'=>10001, 'err_msg'=>'活动不存在'));
		}
		$recMap['act_id'] = $id;
		$recMap['type'] = 1;
		$recMap['user_id'] = $this->user['id'];
		$count = M("PScoreRecord")->where($recMap)->count();
		if ($count) {
			$this->ajaxReturn(array('err_code'=>10002, 'err_msg'=>'您已报名该活动'));
		}

        $expire=M('PConfig')->where(array('key'=>'task_expire'))->find();


		$recMap['score'] = $act['enroll_score'];
        $recMap['consume'] = $act['enroll_score'];
        $recMap['expire_time']=time()+$expire['value']*3600*24;

        $recMap['add_time'] = time();
		$res = M("PScoreRecord")->add($recMap);
		if ($res) {
			$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'报名成功'));
		}else{
			$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'报名失败，请稍后再试'));
		}
	}

	//兑换记录
	public function record()
	{
		$pageSize  = 100;
		$pageIndex = I('post.page', 1, 'intval');

		$map['r.is_deleted'] = 0;
		$map['r.user_id'] = $this->user['id'];
		$map['r.type'] = 3;
		$total = M("PScoreRecord")->alias('r')->where($map)->count();
		$page = $this->pagination($total, $pageSize ,$pageIndex);
		if ($total) {
			$list = M("PScoreRecord")->alias('r')
			      ->field('r.score,r.add_time,e.name')
			      ->join('__P_EXCHANGE__ e ON e.id = r.act_id', 'LEFT')
			      ->where($map)->order('r.id desc')
			      ->limit($page['offset'], $page['limit'])
			      ->select();
			if(!$list){
				$list = array();
			}
			foreach ($list as $k => $v) {
				$list[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
				$list[$k]['score'] = abs($v['score']);
			}
			$res = array('data'=>$list, 'page'=>$page);
		}else{
			$res = array('data'=>array(),'page'=>$page);
		}
		$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$res));
	}

	//抽奖记录
	public function lotteryRecord()
	{
		$pageSize  = 100;
		$pageIndex = I('post.page', 1, 'intval');

		$map['r.is_deleted'] = 0;
		$map['r.user_id'] = $this->user['id'];
		$map['r.type'] = 4;
		$total = M("PScoreRecord")->alias('r')->where($map)->count();
		$page = $this->pagination($total, $pageSize ,$pageIndex);
		if ($total) {
			$list = M("PScoreRecord")->alias('r')
			      ->field('r.score,r.add_time,r.prize_name')
			      //->join('__P_EXCHANGE__ e ON e.id = r.act_id', 'LEFT')
			      ->where($map)->order('r.id desc')
			      ->limit($page['offset'], $page['limit'])
			      ->select();
			if(!$list){
				$list = array();
			}
			foreach ($list as $k => $v) {
				$list[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
				$list[$k]['score'] = abs($v['score']);
			}
			$res = array('data'=>$list, 'page'=>$page);
		}else{
			$res = array('data'=>array(),'page'=>$page);
		}
		$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$res));	
	}

	//积分明细
	public function detail()
	{
		$pageSize  = 100;
		$pageIndex = I('post.page', 1, 'intval');

		$map['r.is_deleted'] = 0;
		$map['r.user_id'] = $this->user['id'];
		$map['r.score'] = array('neq', 0);
		$total = M("PScoreRecord")->alias('r')->where($map)->count();
		$page = $this->pagination($total, $pageSize ,$pageIndex);
		if ($total) {
			$list = M("PScoreRecord")->alias('r')
			      ->field('r.score,r.add_time,r.type')
			    //  ->join('__P_EXCHANGE__ e ON e.id = r.act_id', 'LEFT')
			      ->where($map)->order('r.id desc')
			      ->limit($page['offset'], $page['limit'])
			      ->select();
			if(!$list){
				$list = array();
			}
			foreach ($list as $k => $v) {
				$list[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
				if($v['score'] > 0){
					$list[$k]['operate_type'] = '增加';
					$list[$k]['score'] = '+'.$v['score'];
				}else{
					$list[$k]['operate_type'] = '减少';
				}
				$list[$k]['type'] = $this->scoreType[$v['type']];
			}
			$res = array('data'=>$list, 'page'=>$page);
		}else{
			$res = array('data'=>array(),'page'=>$page);
		}
		$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$res));
	}

	//签到与连续签到
	public function signIn()
	{
		$map['user_id'] = $this->user['id'];

        $expire=M('PConfig')->where(array('key'=>'sign_expire'))->find();

		//查找今天是否已经签到了

		$todayID=date("Y-m-d");
	    $yestodayID=date("Y-m-d",strtotime("-1 day"));

        //查找今天有没有签到
        $map['sign_date']=$todayID;
		$todaySign = M('PSign')->where($map)->find();
		if($todaySign) {
			$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'您今天已签到，明天继续努力'));
		}

		//查找昨天有没有签到
        $map['sign_date']=$yestodayID;
		$yestodaySign = M('PSign')->where($map)->find();

		$signCount=0;  //今天签到总次数

		$canAddLottery=0;

        if($yestodaySign) {
            $signCount=$yestodaySign['days'];
        }
        if($signCount==6){      //上次签到已经是第6次了，这次第7次要奖励
            $signCount+=1;
            $canAddLottery=1;
        }
        else if($signCount==7){      //上次签到是第6次了，这次变回第1次
            $signCount=1;
        }
        else{
            $signCount+=1;
        }
        $newSign['user_id'] = $this->user['id'];
	    $newSign['add_time'] = time();
		$newSign['type'] = 6;
		$newSign['days'] = $signCount;
		$newSign['sign_date'] = $todayID;
		M('PSign')->startTrans();
		$res = M('PSign')->add($newSign);

        if($res) {
			$newScore['user_id'] = $this->user['id'];
			$newScore['act_id'] = 0;
			$newScore['type'] = 6;
			$newScore['score'] = 0;
			$newScore['add_time'] = time();
			$newScore['is_deleted'] = 0;
			$newScore['prize_id'] = $res;
            $newScore['expire_time']=time()+$expire['value']*3600*24;
			M('PScoreRecord')->startTrans();
			$score = M('PScoreRecord')->add($newScore);
			$newScore['signDays'] = $signCount;
			if($score) {
			    $isSuccess=1;
			    //满7天，送一次抽奖机会
			    if($canAddLottery){
            		$userInfo = M("PUser")->where(array("id"=>$this->user['id'], "is_deleted"=>0))->find();
            		if($userInfo){
            		    $userInfo["lottery_time"]+=1;
            		    M("PUser")->where(array("id"=>$this->user['id'], "is_deleted"=>0))->save($userInfo);
            		}
            		else{
            		    $isSuccess=0;
            		    $this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'签到失败，插入记录失败'));
            		}
			    }
			    if($isSuccess){
			        M('PScoreRecord')->commit();
    				M('PSign')->commit();
    				$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>$newScore));
    			}
			}
			M('PScoreRecord')->rollback();
		}
        M('PSign')->rollback();
		$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'签到失败，插入记录失败'));
	}

	public function exchange()
	{
		$prize = I('post.prize', 0, 'intval');
		if($prize <= 0){
			$this->ajaxReturn(array('err_code'=>10001, 'err_msg'=>'要兑换的礼品不存在'));
		}

		$timeMap['is_deleted'] = 0;
		$timeMap['status'] = 1;
		$act = M("PActivity")->where($timeMap)->field('start_time,end_time')
			->order('id desc')->find();

		$now = time();
		if($now < $act['start_time']){
			$this->ajaxReturn(array('err_code'=>20001, 'err_msg'=>'礼品兑换尚未开放'));
		}
		if($now > $act['end_time']){
			$this->ajaxReturn(array('err_code'=>20002, 'err_msg'=>'礼品兑换已结束'));
		}

		$prizeInfo = M("PExchange")->where(array('id'=>$prize,'is_deleted'=>0))->find();
		if (!$prizeInfo) {
			$this->ajaxReturn(array('err_code'=>10002, 'err_msg'=>'要兑换的礼品不存在'));
		}
		if($prizeInfo['sku'] <= 0){
			$this->ajaxReturn(array('err_code'=>10003, 'err_msg'=>'礼品库存不足，无法兑换'));
		}
		if($this->user['score'] < $prizeInfo['score']){
			$this->ajaxReturn(array('err_code'=>10004, 'err_msg'=>'积分不足，无法兑换'));
		}
		
        M()->startTrans();

		$rec['user_id'] = $this->user['id'];
		$rec['act_id'] = $prize;
		$rec['type'] = 3;
		$rec['score'] = -$prizeInfo['score'];
		$rec['add_time'] = time();
        $scoreRec = M("PScoreRecord")->add($rec);
        if (!$scoreRec) {
        	$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'兑换失败'));
        }
        consume_score($this->user['id'],$prizeInfo['score']);
        $prizeMap['id'] = $prize;
        $prizeMap['sku'] = array('gt', 0);
        $prizeMap['is_deleted'] = 0;
  		$decKu = M("PExchange")->where($prizeMap)->setDec("sku", 1);
  		if($decKu){
            M()->commit();
  			$this->ajaxReturn(array('err_code'=>200, 'err_msg'=>'兑换成功'));
  		}else{
            M()->rollback();
  			$this->ajaxReturn(array('err_code'=>50000, 'err_msg'=>'兑换失败'));
  		}

	}
	private function pagination($total, $pageSize, $pageIndex)
	{
	    $page = array();
	    $totalPages = ceil($total / $pageSize);
	    $pageIndex <= 0 and $pageIndex = 1;
	    $offset = ($pageIndex - 1) * $pageSize;

	    $page['limit'] = $pageSize;
	    $page['offset'] = $offset;
	    $page['total'] = (int)$total;//总条目数
	    $page['total_pages'] = (int)$totalPages;//总页数
	    $page['current_page'] = $pageIndex;//当前页数
	    $page['has_nextpage'] = $totalPages > $pageIndex;//是否还有下一页
	    return $page;
	}
	
}
